﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Microsoft.Reporting.WinForms;
using System.IO;

namespace TMS
{
    public partial class ProductCardControl : UserControl
    {
        private bool warehouseListOfProdutsLoaded = false;
       
        Product prod = new Product();
        DataTable tableDispatch = new DataTable();
        DataTable tableReceive = new DataTable();
        DataTable tableWorkOrder = new DataTable();
        DataSet data = new DataSet();
        string ADD = "Name LIKE '%'";
        string ADDK = "K LIKE '%'";
        Categories cat = new Categories();
        Users ActivUser = Program.GetActiveUser;


        public ProductCardControl()
        {
            this.Cursor = Cursors.WaitCursor;
            if (!warehouseListOfProdutsLoaded)
            {
                warehouseListOfProdutsLoaded = true;
            }


            InitializeComponent();
            {
                tableReceive = prod.GetProductCardReceiveNotes();
                DataColumn K = new DataColumn("K", typeof(String));
                K.DefaultValue = "1";
                tableReceive.Columns.Add(K);
                DataColumn P = new DataColumn("P", typeof(String));
                P.DefaultValue = "1";
                tableReceive.Columns.Add(P);
                Int32 i = 0;
                foreach (DataRow row in tableReceive.Rows)
                {

                    try
                    {
                        tableReceive.Rows[i][8] = Convert.ToDecimal(row.ItemArray[12]).ToString("N2");
                    }
                    catch
                    {
                        tableReceive.Rows[i][8] = "0";
                    }
                    i++;

                }
                
                tableReceive.Columns.Remove("AveTotalPrice");
            }
            {
                tableDispatch = prod.GetProductCardDispatchNotes();
                DataColumn K = new DataColumn("K", typeof(String));
                K.DefaultValue = "-1";
                tableDispatch.Columns.Add(K);
                DataColumn P = new DataColumn("P", typeof(String));
                P.DefaultValue = "2";
                tableDispatch.Columns.Add(P);
            }
            {
                tableWorkOrder = prod.GetProductCardWorkOrder();
                DataColumn K = new DataColumn("K", typeof(String));
                K.DefaultValue = "-1";
                tableWorkOrder.Columns.Add(K);
                DataColumn P = new DataColumn("P", typeof(String));
                P.DefaultValue = "3";
                tableWorkOrder.Columns.Add(P);

            }
            tableReceive.Merge(tableDispatch,false);
            tableReceive.Merge(tableWorkOrder, false);
            //Int32 i = 0;
            //foreach (DataRow row in table.Rows)
            //{
            //    table.Rows[i].ItemArray[13]="1";
            //    i++;
            //}
            dgvWarehouseProductsList.DataSource = tableReceive;
            dateTimeFrom.Value = Convert.ToDateTime("01.01." + DateTime.Today.Year.ToString());
            dgvWarehouseProductsList.Columns[0].HeaderText = "Бр.";
            dgvWarehouseProductsList.Columns[1].HeaderText = "Датум";
            dgvWarehouseProductsList.Columns[2].HeaderText = "Коминтент";
            dgvWarehouseProductsList.Columns[3].HeaderText = "Бр. на пр.";
            dgvWarehouseProductsList.Columns[4].HeaderText = "Име";
            //dgvWarehouseProductsList.Columns[4].Visible = false;

            dgvWarehouseProductsList.Columns[5].HeaderText = "Опис";
            dgvWarehouseProductsList.Columns[6].HeaderText = "Количина";
            dgvWarehouseProductsList.Columns[7].HeaderText = "Ед. мрека";
            dgvWarehouseProductsList.Columns[8].HeaderText = "Цена";
            //if (!ActivUser.Finance)
            //dgvWarehouseProductsList.Columns[5].Visible = false;
            //dgvWarehouseProductsList.Columns[5].DefaultCellStyle.Format = "N2";

            dgvWarehouseProductsList.Columns[9].Visible = false;
            dgvWarehouseProductsList.Columns[10].Visible = false;
            dgvWarehouseProductsList.Columns[11].Visible = false;
            dgvWarehouseProductsList.Columns[12].Visible = false;
            dgvWarehouseProductsList.Columns[13].Visible = false;
            //dgvWarehouseProductsList.Columns[10].Visible = false;
            //dgvWarehouseProductsList.Columns[11].Visible = false;
            cmbCategory1.DisplayMember = "name";
            cmbCategory1.ValueMember = "id";
            cmbCategory2.DisplayMember = "name";
            cmbCategory2.ValueMember = "id";
            cmbCategory3.DisplayMember = "name";
            cmbCategory3.ValueMember = "id";
            cmbProductList.DisplayMember = "Name";
            cmbProductList.ValueMember = "Name";
            grbAddProduct.Visible = true;

            if (Program.GetActiveUser.Finance == false)
            {
                dgvWarehouseProductsList.Columns[8].Visible = false;
                ToStTotalPrice.Visible = false;
                txtTotalPrice.Visible = false;
            }

            this.Cursor = Cursors.Default;
            
        }

      

        private void btnNewReceiveNote_Click(object sender, EventArgs e)
        {
            this.Dispose();
            DataGridView tmp = new DataGridView();
            tmp.RowCount = 1;
            tmp.ColumnCount = 1;
            tmp.Rows[0].Cells[0].Value = 0;
            Program.GetMainForm.ShowControl(ControlsEnum.RECEIVE_NOTE_CONTROL,tmp.Rows[0]);
        }

        private void btnNewDispatchNote_Click(object sender, EventArgs e)
        {
            this.Dispose();
            Program.GetMainForm.ShowControl(ControlsEnum.DISPATCH_NOTE_CONTROL);
        }


        
      
        private void cmbCategory1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbCategory1.Items.Count == 0) cmbCategory1.DataSource = cat.GetAllCategory1().Tables[0];
            else
            {

                if (cmbCategory1.SelectedValue.ToString() == "1")
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2(cmbCategory1.SelectedValue.ToString()).Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3(cmbCategory1.SelectedValue.ToString(), "").Tables[0];
                    
                }
            }
            

        }

        private void cmbCategory2_SelectedValueChanged(object sender, EventArgs e)
        {

            if (cmbCategory2.Items.Count == 0) cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
            else
            {
                if (cmbCategory2.SelectedValue.ToString() == "1")
                {
                  //  cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", cmbCategory2.SelectedValue.ToString()).Tables[0];
                   
                }
            }

        }

        private void cmbCategory3_SelectedValueChanged(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (cmbCategory3.Items.Count == 0) cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
            if (cmbCategory2.SelectedValue.ToString() != "System.Data.DataRowView")
                if (cmbCategory3.SelectedValue.ToString() != "System.Data.DataRowView")
                {

                    data = prod.GetProductFromDB(cmbCategory1.SelectedValue.ToString(), cmbCategory2.SelectedValue.ToString(), cmbCategory3.SelectedValue.ToString());
                    cmbProductList.Text = "";
                    cmbProductList.DataSource = data.Tables[0];
                   
                    cmbProductList.Update();
                }
            this.Cursor = Cursors.Default;

        }

        private void cmbProductList_SelectedValueChanged(object sender, EventArgs e)
        {
            dgvWarehouseProductsList.Update();
            if (radbtnNameSearch.Checked==true)
            if (cmbProductList.SelectedValue.ToString()!="System.Data.DataRowView")
            ADD = string.Format("Name ='" + cmbProductList.SelectedValue.ToString() + "'");
            dateTimeFrom_ValueChanged(sender, e);
            dgvWarehouseProductsList.Update();
        }

       

        private void btnShowAll_Click(object sender, EventArgs e)
        {
            tableReceive.DefaultView.RowFilter = string.Format("Name LIKE '%'");
            dgvWarehouseProductsList.Update();
        }

        private void dgvWarehouseProductsList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape) this.Dispose();
            return base.ProcessCmdKey(ref msg, keyData);
        }

        

        private void dgvWarehouseProductsList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            Int32 i = 0;

            foreach (DataGridViewRow row in dgvWarehouseProductsList.Rows)
            {
                if (Convert.ToInt32(row.Cells[13].Value) ==1)
                    row.DefaultCellStyle.ForeColor = Color.DarkCyan;
                else if (Convert.ToInt32(row.Cells[13].Value) ==2)
                    row.DefaultCellStyle.ForeColor = Color.Red;
                else
                    row.DefaultCellStyle.ForeColor = Color.DarkOrange;
                i++;
            }
        }

        private void dgvWarehouseProductsList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((dgvWarehouseProductsList.CurrentCell.ColumnIndex==3)&&(e.RowIndex!=-1))
            MessageBox.Show("Минимална залиха "+dgvWarehouseProductsList.CurrentRow.Cells[8].Value.ToString());
        }

        private void rdbtnCategory1Search_CheckedChanged(object sender, EventArgs e)
        {   
            if (rdbtnCategory1Search.Checked == true)
            ADD = string.Format("Category_1 ='" + cmbCategory1.SelectedValue.ToString() + "'");
            dateTimeFrom_ValueChanged(sender, e);
            dgvWarehouseProductsList.Update();
        }

        private void rdbtnCategory2Search_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnCategory2Search.Checked == true)
            ADD = string.Format("Category_2 ='" + cmbCategory2.SelectedValue.ToString() + "'");
            dateTimeFrom_ValueChanged(sender, e);
            dgvWarehouseProductsList.Update();
        }

        private void rdbtnCategory3Search_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnCategory3Search.Checked == true)
            ADD = string.Format("Category_3 ='" + cmbCategory3.SelectedValue.ToString() + "'");
            dateTimeFrom_ValueChanged(sender, e);
            dgvWarehouseProductsList.Update();
        }

        private void toolStocktaking_Click(object sender, EventArgs e)
        {
            this.Hide();
            Program.GetMainForm.ShowControl(ControlsEnum.STOCKTAKING_CONTROL);
        }

        private void dateTimeFrom_ValueChanged(object sender, EventArgs e)
        {
            tableReceive.DefaultView.RowFilter = string.Format("Date >'" + dateTimeFrom.Value.ToString() + "'AND Date<'" + dateTimeTo.Value.ToString() + "' AND " + ADD + " AND " + ADDK);

        }

        private void dateTimeTo_ValueChanged(object sender, EventArgs e)
        {
            tableReceive.DefaultView.RowFilter = string.Format("Date >'" + dateTimeFrom.Value.ToString() + "'AND Date<'" + dateTimeTo.Value.ToString() + "' AND " + ADD + " AND " + ADDK);

        }

        private void rbINOUT_CheckedChanged(object sender, EventArgs e)
        {
            if (rbINOUT.Checked)
            ADDK = "K LIKE '%'";
            dateTimeFrom_ValueChanged(sender, e);
        }

        private void rbIN_CheckedChanged(object sender, EventArgs e)
        {
            if (rbIN.Checked)
                ADDK = "K = '1'";
            dateTimeFrom_ValueChanged(sender, e);
        }

        private void rbOUT_CheckedChanged(object sender, EventArgs e)
        {
            if (rbOUT.Checked)
                ADDK = "K= '-1'";
            dateTimeFrom_ValueChanged(sender, e);
        }

        private void btnTotalPrice_Click(object sender, EventArgs e)
        {
            Decimal TotalPrice = 0;
            foreach (DataGridViewRow row in dgvWarehouseProductsList.Rows)
            {
                try
                {
                    TotalPrice += Convert.ToInt32(row.Cells[6].Value) * Convert.ToDecimal(row.Cells[8].Value) * Convert.ToInt32(row.Cells[12].Value);
                }
                catch
                {
                   // MessageBox.Show("Нема набавна цена за:" + row.Cells[5].Value.ToString() + "\nПроизводот ќе биде игнориран\nЦената треба да ја внесе администраторот на TMS");
                }
            }
            txtTotalPrice.Text = TotalPrice.ToString("N2");
        }

        private void ToStBack_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Back())
                this.Dispose();
        }


        private void ToStForward_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Forward())
                this.Dispose();
        }

        }

}
